package maven;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
public class TreeNode implements Serializable {

    private Long id;
    /**
     * jar包名称
     */
    private String jarName;
    private Long parentId;
    private Scope scope;
    private List<TreeNode> treeNodes;

    private DependencyMode dependencyMode;
    private String projectName;

    private Long kbSize;

    private String version;

    private String group;

    // 递归收集子节点
    private void collectChildren(TreeNode node, List<TreeNode> result) {
        if (node.treeNodes != null) {
            for (TreeNode child : node.treeNodes) {
                result.add(child);
                collectChildren(child, result);
            }
        }
    }

    public List<TreeNode> getAllChildren() {
        return getAllChildren(false);
    }
    // 获取所有子节点
    public List<TreeNode> getAllChildren(boolean includingItself) {
        List<TreeNode> allChildren = new ArrayList<>();
        if (includingItself) {
            allChildren.add(this);
        }
        collectChildren(this, allChildren);
        return allChildren;
    }

    public boolean sameJar(TreeNode treeNode) {
        return this.jarName == treeNode.getJarName()
                && this.group == treeNode.getGroup()
                ;
    }

    public String getGroupJarName() {
        if (group == null || jarName == null) {
            throw new RuntimeException("treenode 缺失数据");
        }
        return group + ":" + jarName;
    }

    public  Double formatSize() {
        BigDecimal bigDecimal = new BigDecimal(this.kbSize);
        BigDecimal divide = bigDecimal.divide(new BigDecimal(1024));

        return divide.doubleValue();
    }

    public String formatSheetName() {
        String groupJarName = getGroupJarName();
        groupJarName = groupJarName.replaceAll(":","_");
        if (groupJarName.length() > 31) {
            String collect = Arrays.stream(group.split("\\.")).map(s -> s.substring(0, 1)).collect(Collectors.joining("."));
            groupJarName = collect + "_" + jarName;
            if (groupJarName.length() > 31) {
                groupJarName = groupJarName.substring(0,31);
            }

        }
        return groupJarName;
    }
}